// 云函数入口文件
const cloud = require('wx-server-sdk')
const dayjs = require('dayjs')
dayjs.extend(require('dayjs/plugin/isoWeek'))
dayjs.extend(require('dayjs/plugin/utc'))
dayjs.extend(require('dayjs/plugin/timezone'))
dayjs.tz.setDefault('Asia/Shanghai')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async event => {
  const { sn } = event
  if (!sn) {
    throw new Error('no sn')
  }

  const now = dayjs().tz()
  const today = now.format('YYYY-MM-DD')
  const week = now.startOf('isoWeek').format('YYYY-MM-DD')

  const {
    data: [sData],
  } = await db.collection('screen').where({ sn }).get()
  if (!sData) {
    throw new Error('screen not found')
  }

  await db
    .collection('screen')
    .where({ sn })
    .update({ data: { status: 1 } })

  let { data: promotionData } = await db
    .collection('promotion-cast')
    .field({ promotion: true, currQuota: true })
    .where({ screens: { _id: sData._id }, week })
    .get()
  promotionData = promotionData.map(v => {
    const { _id, promotion, currQuota } = v
    const {
      name,
      imgUrls: [imgUrl],
      price,
      originalPrice,
      quota,
      store,
    } = promotion
    const { address, imgUrl: avatarUrl } = store
    const qrcodeUrl = `https://zhihu.com/qrcode?url=https://wbg.shihangdushu.com/customer/promotion/${_id}/screen/${sData._id}`

    return {
      type: 'promotion',
      _id,
      name,
      address,
      price,
      originalPrice,
      avatarUrl,
      imgUrl,
      qrcodeUrl,
      quota: {
        curr: currQuota[today],
        total: quota,
      },
      bullets: [],
    }
  })

  let { data: simpleData } = await db
    .collection('image-cast')
    .where({ screenId: sData._id, date: today })
    .get()
  simpleData = []
    .concat(...simpleData.map(v => v.resources.map(v => v.url)))
    .map(v => ({ type: 'simple', imgUrl: v }))

  return [].concat(promotionData, simpleData)
}
